import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ChatChannel implements Runnable {
    private Socket socket;
    private ObjectInputStream ois;
    private String name;
    private ObjectOutputStream oos;
    private static Map<String,ObjectOutputStream>allmap = new HashMap<String,ObjectOutputStream>();

    public ChatChannel(Socket socket){
        this.socket=socket;
    }
    public void run() {
        try {
            recvNameAndEchoHello();
            //服务器端增加收发代码
            while(true){
                String msg= (String) ois.readObject();
               int start = msg.indexOf("向")+1;
                int end = msg.indexOf("发送");
                if (start>-1 && end>-1 && start<end){
                    //
                    String secretName = msg.substring(start,end);
                    String secretMsg = msg.substring(end+1);
                    //
                    ObjectOutputStream secretoos = allmap.get(secretName);
                    System.out.println(name+"悄悄对"+secretName+"说"+secretMsg);
                    secretoos.writeObject(name+"悄悄对你说"+secretMsg);
                }
                else {
                    System.out.println(name + "说"+ msg);
                    sendToall(name + "说" + msg);
                }
            }
        } catch (IOException e) {

           //从allmap中删除name和oos
            allmap.remove(name);
            try {
                sendToall(name+"退出聊天室");
                //通知其他客户端用户该用户下线
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
//遍历所有客户端输出流，向每个用户端发送消息
    private void sendToall(String msg) throws IOException {
        for (ObjectOutputStream oos1:allmap.values()){
            oos1.writeObject(name +"说:"+ msg);
            oos1.flush();
        }
    }

    private void recvNameAndEchoHello() throws IOException, ClassNotFoundException {
        //获得socket对应的输入流对象，准备接收客户端的输入
        InputStream is= socket.getInputStream();
        //将最基础的InputStream对象包装成对象流
        ois = new ObjectInputStream(is);
        //调用对象流的readObject()方法接收客户端的输入的姓名
        name = (String) ois.readObject();

        //输出客户端进入聊天室的提示信息
        System.out.println(name +"进入聊天室");
        sendToall(name +"进入聊天室");

        //向客户端发送欢迎信息
        //获得与客户端通信的输出流对象
        OutputStream os=socket.getOutputStream();
        //将最基础的OutputStream对象包装成对象流
        oos = new ObjectOutputStream(os);
        //调用对象流的writeObject()方法向客户端发送欢迎信息
        oos.writeObject(name + "，您好!欢迎您进入聊天室");
        oos.flush();
        allmap.put(name,oos);
    }

}
